package com.king.modules.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.king.common.exception.AssertHelper;
import com.king.common.utils.SecurityUtils;
import com.king.common.utils.uuid.SnowFlakeUtil;
import com.king.framework.base.service.impl.YyBaseServiceImpl;
import com.king.modules.system.domain.SysGroupMenuEntity;
import com.king.modules.system.domain.SysMenuEntity;
import com.king.modules.system.domain.SysOrgEntity;
import com.king.modules.system.domain.vo.GroupMenuDTO;
import com.king.modules.system.mapper.SysGroupMenuMapper;
import com.king.modules.system.service.SysMenuService;
import com.king.modules.system.service.SysOrgService;
import com.king.modules.system.service.SysGroupMenuService;
import com.king.modules.system.service.SysRoleMenuService;

/**
 * 消息 业务层
 * 
 * @author liusheng
 */
@Service
public class SysGroupMenuServiceImpl extends YyBaseServiceImpl<SysGroupMenuMapper, SysGroupMenuEntity, Long> implements SysGroupMenuService {

//	private Logger logger = LoggerFactory.getLogger(GroupMenuServiceImpl.class);

	@SuppressWarnings("unused")
	@Autowired
	private SysGroupMenuMapper groupMenuMapper;
	@Autowired
	private SysOrgService orgService;
	@Autowired
	private SysMenuService menuService;
	@Autowired
	private SysRoleMenuService sysRoleMenuService;

	
	
	
	@Override
	public void beforeAdd(SysGroupMenuEntity entity) throws Exception {
		entity.setGroupid(entity.getOwnorgid());//设置集团id
		super.beforeAdd(entity);
	}

	@Override
	public List<SysGroupMenuEntity> findByGroupid(Long ownorgid) {
		QueryWrapper<SysGroupMenuEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("ownorgid", ownorgid);
		return list(queryWrapper);
	}

	@Override
	public List<SysMenuEntity> queryMenuRes(Long ownorgid) throws Exception {
		List<SysGroupMenuEntity> groupMenuList = findByGroupid(ownorgid);
		Set<Long> idSet = groupMenuList.stream().map(SysGroupMenuEntity :: getMenuid).collect(Collectors.toSet());
		List<SysMenuEntity> menuList =  (List<SysMenuEntity>) menuService.findAll();//TODO 后面多租户怎么判断用户自增的菜单
		for(SysMenuEntity menu : menuList){
			if(idSet.contains(menu.getId())){
				menu.setChecked(true);
			}else{
				menu.setChecked(false);
			}
		}
		return menuList;		
	}
	
	/**
	 * 查询当前用户所在集团的菜单
	 */
	@Override
	public List<SysGroupMenuEntity> queryOwnMenuRes(SysMenuEntity form) {
		return menuService.queryOwnMenuRes(form);
	}

	@Transactional(readOnly = false, rollbackFor = { Exception.class })
	@Override
	public void auth(GroupMenuDTO vo) throws Exception {
		AssertHelper.getInstance().checkException(!SecurityUtils.isAdmin(), "权限不足");
		
		Long ownorgid = vo.getOwnorgid();
		AssertHelper.getInstance().checkNullException(ownorgid, "请选择企业");

		SysOrgEntity org = orgService.findByPK(ownorgid);
		AssertHelper.getInstance().checkException(org == null, "集团不存在:" + ownorgid);

		List<SysGroupMenuEntity> dbGroupMenuList = findByGroupid(ownorgid);
		Set<Long> dbMenuIds = dbGroupMenuList.stream().map(SysGroupMenuEntity::getMenuid).collect(Collectors.toSet());

		Long[] menuids = vo.getMenuids();
		if (menuids != null) {
			List<SysGroupMenuEntity> entityList = new ArrayList<SysGroupMenuEntity>();
			for (Long menuid : menuids) {
				SysMenuEntity menu = menuService.findByPK(menuid);
				AssertHelper.getInstance().checkException(org == null, "菜单不存在:" + menuid);

				if (dbMenuIds.contains(menuid)) {
					continue;
				}
				SysGroupMenuEntity entity = new SysGroupMenuEntity();
				entity.setId(SnowFlakeUtil.getInstance().nextId());
				entity.setOwnorgid(ownorgid);
				entity.setMenuid(menuid);
				entity.setShoworder(menu.getShoworder());
				entity.setMenualias(menu.getNodename());
				entityList.add(entity);
			}
			if (entityList != null) {
//				saveBatch(entityList);
				doAdd(entityList);
			}

			List<Long> delMenuIds = new ArrayList<>();
			List<Long> delGroupMenuIds = new ArrayList<>();
			for (SysGroupMenuEntity gm : dbGroupMenuList) {
				boolean exitMenu = false;
				for (Long menuid : menuids) {
					if (menuid.longValue() == gm.getMenuid().longValue()) {
						exitMenu = true;
						break;
					}
				}
				if (!exitMenu) {
					delMenuIds.add(gm.getMenuid());
					delGroupMenuIds.add(gm.getId());
				}
			}
			if (!CollectionUtils.isEmpty(delGroupMenuIds)) {
				doDelete(delGroupMenuIds.toArray(new Long[delGroupMenuIds.size()]));
				sysRoleMenuService.deleteByGroupidMenuids(ownorgid, delMenuIds);
			}
		}
	}
}